package br.com.felix.easyclearcase.ui.dialogs;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import br.com.felix.easyclearcase.tasks.ClearCaseTask;
import br.com.felix.easyclearcase.tasks.Task;


public class ExecutionReport {
	
	private JTable table;
	private JList area;
	private Object[][]data;
	
	public ExecutionReport(List<Task> tasks){
		int reportTasks = 0;
		for(Task t:tasks){
			if(t.isToAddToReport())reportTasks++;
		}
		data = new Object[reportTasks][2];
		int i=0;
		for(Task task:tasks){
			if(task.isToAddToReport()){
				data[i][0] = task;
				data[i][1] = task.getStatus();
				i++;
			}
		}
		table = new JTable(data, new String[]{"Task","Status"});
		table.addMouseListener(new MouseAdapter(){
			@Override
			public void mousePressed(MouseEvent e) {
				showLogMessage();
			}
		});
		area = new JList();
	}
	
	
	protected void showLogMessage() {
		int row = table.getSelectedRow();
		//This cast is only possible because now ClearCaseTasks are the only ones that goes to the report.
		ClearCaseTask t = (ClearCaseTask) data[row][0];
		String msg = "Log ##########\n"+ t.getLogger().toString() + "\nOutput ###########\n"+t.getOutputLogger().toString();
		DefaultListModel dm = new DefaultListModel();
		String msgs[] = msg.split("\n");
		for(String m:msgs){
			dm.addElement(m);
		}
		area.setModel(dm);
		area.validate();
	}


	public void show(){
		JFrame jfr = new JFrame("Execution Report");
		jfr.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		Container contentPane = jfr.getContentPane();
		contentPane.setLayout(new GridBagLayout());
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.gridx=0;
		gbc.gridy=0;
		gbc.fill = GridBagConstraints.BOTH;
		JScrollPane paneTable = new JScrollPane(table);
		contentPane.add(paneTable,gbc);
		gbc.gridy++;
		JScrollPane paneArea = new JScrollPane(area);
		paneArea.setPreferredSize(new Dimension(700,100));
		paneArea.setAutoscrolls(true);
		contentPane.add(paneArea,gbc);
		
		jfr.setSize(new Dimension(800,600));
		jfr.setVisible(true);
	}
	
}
